package com.baomidou.ant.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.ant.common.Result;
import com.baomidou.ant.config.AlipayConfig;
import com.baomidou.ant.entity.Alipay;
import com.baomidou.ant.entity.User;
import com.baomidou.ant.service.IAlipayService;
import com.baomidou.ant.service.IUserService;
import com.baomidou.ant.vo.Request.RequestOrderInfoVo;
import com.baomidou.ant.vo.Response.ResponseMyAlipayVo;
import com.baomidou.ant.vo.Response.ResponsePayNumsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private IUserService userService;


    //检测实名是否通过
    @ResponseBody
    @GetMapping("/checkRealName/{userId}")
    public Result checkRealName(@PathVariable Integer userId){
        if(alipayService.checkRealName(userId)){
            return Result.getSuccess();
        }else
            return Result.getFailure();
    }

    /**
     * @param response
     * @param request
     * @param
     * @return 利用vo封装数据，更安全，通过result返回跳转数据，利于调用
     */
    @ResponseBody
    @RequestMapping("/pay")
    public Result payMent(HttpServletResponse response, HttpServletRequest request, @RequestBody RequestOrderInfoVo vo) {
        String str = "";
        try {
            //生成订单号
            String orderNumber = IdWorker.getIdStr();
            //生成初始订单
            Alipay alipay = new Alipay();
            alipay.setUserId(vo.getUserId());
            alipay.setPayAmount(vo.getAmount());
            alipay.setOrderNumber(orderNumber);
            alipayService.save(alipay);
            //执行订单
            str = alipayService.aliPay(response, request, vo.getAmount(), orderNumber);
        } catch (IOException e) {
            e.printStackTrace();
            }
        //返回跳转页面
        return Result.getSuccess().setData(str);
    }

    /**
     *
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws IOException
     * 异步通知
     */
    @ResponseBody
    @RequestMapping(value = "/notifyUrl",method = RequestMethod.POST)
    public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("=================================异步回调=====================================");
        PrintWriter out= response.getWriter();
        request.setCharacterEncoding("utf-8");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);

        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            //打印关键信息
            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            /*System.out.println("付款金额="+total_amount);*/

            if(trade_status.equals("TRADE_FINISHED")||trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //支付成功，修改支付状态
                QueryWrapper<Alipay> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("order_number",out_trade_no);
                Alipay alipay=alipayService.getOne(queryWrapper);
                //订单支付成功
                alipay.setStatus("1");
                alipayService.saveOrUpdate(alipay);
                //充值成功
                User user=userService.getById(alipay.getUserId());
                user.setDiamonds(user.getDiamonds()+alipay.getPayAmount()*10);
                userService.saveOrUpdate(user);
            }
            System.out.println("success");

        }else {//验证失败
            System.out.println("fail");
            out.println("fail");
        }
        out.println("success");
    }


    /**
     *
     * @param request
     * @return
     * @throws AlipayApiException
     * 同步通知
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 防止乱码
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //打印三个关键信息
            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修改支付状态
            QueryWrapper<Alipay> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("order_number",out_trade_no);
            Alipay alipay=alipayService.getOne(queryWrapper);
            //订单支付成功
            alipay.setStatus("1");
            alipayService.saveOrUpdate(alipay);
            //充值成功
            User user=userService.getById(alipay.getUserId());
            user.setDiamonds(user.getDiamonds()+alipay.getPayAmount()*10);
            userService.saveOrUpdate(user);

//            payService.updateById(Integer.valueOf(out_trade_no));
//            return "<form name=\"punchout_form\" method=\"get\" action=\"http://www.dageshuang.top/user_index.html\">\n" +
//                    "<input type=\"submit\" value=\"支付成功\" style=\"display:none\" >\n" +
//                    "</form>\n" +
//                    "<script>document.forms[0].submit();</script>";//跳转付款成功页面

            return "success";
        }else{
            return "no";//跳转付款失败页面
        }
    }

    @GetMapping("/reUrl")
    private String reUrl(){ return "user_index"; }

    @ResponseBody
    @GetMapping("/listMyAlipay/{userId}")
    private Result listMyAlipay(@PathVariable Integer userId){
        ResponsePayNumsVo vo=new ResponsePayNumsVo();
        vo.setNum6(alipayService.payNums(userId,6));
        vo.setNum30(alipayService.payNums(userId,30));
        vo.setNum68(alipayService.payNums(userId,68));
        vo.setNum128(alipayService.payNums(userId,128));
        vo.setNum328(alipayService.payNums(userId,328));
        vo.setNum648(alipayService.payNums(userId,648));
        return Result.getSuccess().setData(vo);
    }



}